#include "TcpServer.hpp"
#include <memory>

Respense calculator(const Request& req)
{
    Respense resp(0, 0);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (req.y_ == 0) resp.code_ = 1;
        else resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (req.y_ == 0) resp.code_ = 2;
        else resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }

    return resp;
}

void NetCal(Connection* conn, std::string& request)
{
    logMessage(DEBUG, "Netcal been called, get request: %s", request.c_str());
    // 1.反序列化, 1 + 1  2 + 3
    Request req;
    if (!req.Deserialized(request)) return ;

    // 2.业务处理
    Respense resp = calculator(req);

    // 3.序列化,构建应答
    std::string sendstr = resp.Serialize();
    sendstr = EnCode(sendstr);

    // 4.交给服务器conn,让服务器进行发送
    conn->_outbuffer += sendstr;

    // 5.想办法，让底层的TcpServer，让它开始发送
    //  a.需要由完整的发送逻辑
    //  b.触发发送的数据，一旦我们开启EPOLLOUT，epoll会自动立马触发一次发送事件就绪，如果后续保持发送的开启，epoll会在底层给我们一直发
    conn->_tsvr->EnableReadWrite(conn, true, true);
    std::cout << "##############################" << std::endl;
}

int main()
{
    std::unique_ptr<TcpServer> svr(new TcpServer());
    svr->Dispather(NetCal);

    return 0;
}
